<template>
  <div class="app-container">
    <!-- 账户查询 -->
    <el-card style="margin-bottom:10px;position:relative;">
      <span class="hint">输入框为空时，点击查询，可回到默认样式</span>
      <el-form inline @submit.native.prevent>
        <el-form-item><el-input v-model="userAccount" placeholder="请输入用户名" @keyup.native.enter="findAccountBtn" /></el-form-item>
        <el-button  type="primary" icon="el-icon-search" @click="findAccountBtn">查询</el-button>
        <el-button type="default" @click="userAccount = ''">清空</el-button>
      </el-form>
    </el-card>
    
    <!-- 账户信息 -->
    <el-card>
      <div slot="header">
        <span style="position:absolute;left:50%;font-size:20px;">账户管理</span>
        <div>
          <!-- 添加与批量添加按钮 -->
          <el-button type="primary" size="small" @click="addAccountBtn">添 加</el-button>
          <el-button :disabled="accountStateList.length === 0" type="danger" size="small" @click="batchDeleteAccountBtn">批量删除</el-button>
        </div>
      </div>
      <div>
        <!-- table表格：展示用户信息的地方 -->
        <el-table
          border
          stripe
          @selection-change="handleSelectionChange"
          v-loading="tableLoading"
          :data="userList"
          :default-sort="{prop: 'createTime'}"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column align="center" prop="userName" label="账户名" width="150" />
          <el-table-column align="center" prop="roles" label="角色">
            <template slot-scope="{row}">
              <el-tag
                v-if="role"
                type="primary"
                v-for="(role,index) in row.roles.split(',')"
                :key="index"
              >{{role}}</el-tag>
              <div v-else><el-tag  type="warning">此用户没有权限，请<span class="addAccountSpan" @click="updateAccountBtn(row)">添加</span></el-tag></div>
            </template>
          </el-table-column>
          <el-table-column sortable align="center" prop="createTime" label="创建时间" width="200" />
          <el-table-column label="操作" width="230" align="center">
            <template slot-scope="{row}">
              <el-button @click="assignRole" type="info" size="mini" icon="el-icon-user-solid" title="分配角色" />
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-edit"
                title="修改用户"
                @click="updateAccountBtn(row)"
              />
              <el-popconfirm :title="`确定删除 ${row.userName} 吗?`" @confirm="deleteAccountBtn(row)">
                <el-button
                  style="margin-left:10px"
                  slot="reference"
                  type="danger"
                  size="small"
                  icon="el-icon-delete"
                  title="删除用户"
                />
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 分页器 -->
    <el-pagination
      align="center"
      :current-page="pagination.currentPage"
      :total="pagination.total"
      :page-size="pagination.limit"
      :page-sizes="[3,5,7,9,11]"
      style="padding: 10px 0;"
      layout="prev, pager, next, jumper, ->, sizes, total"
      @size-change="handleLimit"
      @current-change="getAccountInfo"
    />

    <!-- 对话框 :before-close="dialogBeforeClose" -->
    <el-dialog :title="userInfo.id ? '修改账户' : '添加账户'" :visible.sync="dialogFormVisible" width="width">
      <el-form v-model="userInfo">
        <el-form-item label="账户" :label-width="formLabelWidth">
          <el-input v-model="userInfo.userName" style="width:80%;" placeholder="请输入账户"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input v-model="userInfo.userPassword" style="width:80%;" placeholder="请输入账户"></el-input>
        </el-form-item>
        <el-form-item label="权限" :label-width="formLabelWidth">
          <el-checkbox-group v-model="userInfo.roles">
            <el-checkbox label="学生管理" name="roles"></el-checkbox>
            <el-checkbox label="权限管理" name="roles"></el-checkbox>
            <el-checkbox :disabled="admin !== 'admin'" label="超级管理员" name="roles"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateAccount">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="roleDialog"
      width="width">
      <div>分配角色对话框</div>
      <div slot="footer">
        <el-button @click="roleDialog = false">取 消</el-button>
        <el-button type="primary" @click="roleDialog = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "AdminAccount",
  data() {
    return {
      // 存储查询数据
      userAccount: '',
      // 用户信息
      userInfo: {
        userName: "",
        userPassword:'',
        roles: ['学生管理']
      },
      // 控制表格加载显示
      tableLoading:true,
      // 用户信息列表
      userList: [],
      // 分页器
      pagination: {
        currentPage: 1,
        limit: 5,
        total: void 0
      },
      // 控制添加用户对话框显示
      dialogFormVisible: false,
      // 控制角色分配对话框显示
      roleDialog:false,
      // 控制表单宽度
      formLabelWidth: "120px",
      // 收集选中时的账户信息
      accountStateList:[]
    };
  },
  mounted() {
    this.getAccountInfo();
  },
  methods: {
    // 分配角色
    assignRole(){
      this.$message.warning('#_#,此功能正在开发中,可以点击修改，分配权限')
    },
    // 初始化账户信息
    async getAccountInfo(pager = 1) {
      this.pagination.currentPage = pager;
      try {
        let result = await this.$store.dispatch("studentAdminAccount/getFindAccount",this.pagination);
        // console.log('result',result.data)
        if (result.code === 200) {
          let { data,currentPage, limit,total } = result;
          this.userList = data;
          this.pagination.total = total;
          // this.pagination.currentPage = currentPage;
          // this.pagination.limit = limit;
          // 当数据都返回时 loading 关闭
          this.tableLoading = false
        }
      } catch (error) {
        this.$message.error(`*_*,${error.message}`)
      }
    },
    // 分页器， 页面展示数量数量事件
    handleLimit(limit) {
      this.pagination.limit = limit;
      this.getAccountInfo();
    },
    // 添加账户
    addAccountBtn() {
      this.dialogFormVisible = true;  
      this.userInfo = {roles: ['学生管理']}
      // Object.assign(this._data.userInfo,this.$options.data().userInfo)
    },
    // 修改账户信息
    updateAccountBtn(row) {
      this.dialogFormVisible = true;
      let newRow = {...row}
      // 将 目标账户权限分割为数组进行存储
      newRow.roles = row.roles.split(',')
      // row.roles = newRow.roles
      // console.log(row)
      this.userInfo = newRow
    },
    // 添加或修改账户信息
    async addOrUpdateAccount(){
      try {
        // 获取添加账户信息
        let result = await this.$store.dispatch('studentAdminAccount/getAddUserAccount', this.userInfo);
        if(result.code === 200){
          // 添加成功后 关闭弹出层
          this.dialogFormVisible = false
          this.$message.success(`${this.userInfo.id ? '^_^,修改成功':'^_^,添加成功'}`)
          this.getAccountInfo(this.pagination.currentPage)
        }
      } catch (error) {
        this.$message.error(`*_*,${error.message}`)
      }
    },
    // 删除单个账户
    async deleteAccountBtn(row) {
      try {
        let result = await this.$store.dispatch('studentAdminAccount/getDeleteUserAccount', row.id);
        if(result.code === 200){
          this.$message.success('^_^,删除成功')
          this.getAccountInfo(this.userList.length > 1 ? this.pagination.currentPage : this.pagination.currentPage - 1)
        }
      } catch (error) {
        this.$message.error(`*_*,${error.message}`)
      }
    },
    // 批量删除账户
    async batchDeleteAccountBtn() {
      let userIdArr = this.accountStateList.map(item => {
        return item.id
      })
      try {
        let result = await this.$store.dispatch('studentAdminAccount/getBatchDeleteUserAccount',userIdArr);
        if(result.code === 200){
          this.$message.success('^_^,批量删除成功')
          this.getAccountInfo(this.userList >= 1 ? this.pagination.currentPage : this.pagination.currentPage - 1)
        }
      } catch (error) {
        this.$message.error(`*_*,${error.messages}`)
      }
    },
    // 账户选中事件
    handleSelectionChange(rows){
      this.accountStateList = rows
    },
    // 查询账户
    async findAccountBtn(){
      // 当查询框为空， 加载初始化状态
      if(!this.userAccount){
        return this.getAccountInfo()
      }
      try {
        let result = await this.$store.dispatch('studentAdminAccount/getFindUserAccount', this.userAccount);
        if(result.code === 200){
          this.$message.success('^_^')
          this.userList = result.data
        }
      } catch (error) {
        this.$message.warning(`*_*,${error.message}`)
      }
    },
    
  },
  computed:{
    // 获取此账户， 作用当此账户为 超级管理员时 可以将用户也设置为超级管理
    admin(){
      return sessionStorage.getItem('userName')
    },
    // test(){
    //   return 
    // }
  }
};
</script>

<style lang="less" scoped>
// span这种添加文字样式
.addAccountSpan{
  color:red;
  margin-left:5px;
  cursor:pointer;
  text-decoration:underline;
}

.el-tag {
  margin-right: 10px;
}
/deep/.el-card__body:nth-of-type(1) {
  padding-bottom: 0;
  
}
// 查询框提示
  .hint{
    color:#999;
    font-size:12px;
    position:absolute;
    left:22px;
    top:1px;
    
  }
</style>